package com.qunar.tech.team12.shell.command;

import com.google.common.collect.Maps;
import com.qunar.tech.team12.shell.command.annotation.Cmd;
import com.qunar.tech.team12.shell.exception.NoSuchCommandException;
import com.qunar.tech.team12.shell.util.ClassUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;


/**
 * Created by mzy on 14-5-12.
 */
public class CommandLoader {

    private static Map<String, Command> map = Maps.newHashMap();
    private static Logger LOG = LoggerFactory.getLogger(CommandLoader.class);

    static {//init map
        List<Class<?>> classes = ClassUtil.getClassList(CommandLoader.class.getPackage().getName() + ".impl", false);
        for (Class clazz : classes) {
            if (clazz.isAnnotationPresent(Cmd.class)) {
                Cmd cmd = (Cmd) clazz.getAnnotation(Cmd.class);
                Command command = null;
                try {
                    command = new Command(clazz);
                } catch (NoSuchCommandException e) {
                    LOG.error("No such command", e);
                }
                map.put(cmd.name(), command);
            }
        }
    }

    public static Command getCommand(String commandName) throws NoSuchCommandException {
        if (map.get(commandName) != null) {
            return map.get(commandName);
        } else {
            throw new NoSuchCommandException(commandName);
        }
    }
}
